package com.youzikj.wx.core.comm;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import net.sf.json.JSONObject;

import com.youzikj.wx.comm.oauth2.AdvancedUtil;
import com.youzikj.wx.comm.oauth2.SNSUserInfo;
import com.youzikj.wx.comm.oauth2.WeixinOauth2Token;
import com.youzikj.wx.comm.respmsg.RespTextMessage;
import com.youzikj.wx.comm.util.CommonUtil;
import com.youzikj.wx.comm.util.MessageUtil;
import com.youzikj.wx.pay.Configure;
import com.youzikj.wx.pay.hongbao.MoneyUtils;

public class Utils {
	
	private final static String WX_FONT_COLOR_WARN="#F70909";
	private final static String WX_FONT_COLOR_NORMAL="#173177";
	
	public final static String url ="https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
	
	/**
	 * 发送红包	
	 * @param opendid
	 * @param price
	 * @return
	 */
	public static String sendHb(String opendid,int price) {
		String mch_billno = MoneyUtils.getMch_billno();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("nonce_str", MoneyUtils.buildRandom());//随机字符串
		map.put("mch_billno", mch_billno);//商户订单
		map.put("mch_id", "1419995602");//商户号
		map.put("wxappid", "wxca78deeb014de180");//商户appid
		map.put("nick_name", "柚子科技");//提供方名称
		map.put("send_name", "微友传单");//用户名
		map.put("re_openid", opendid);//用户openid
		map.put("total_amount", price);//付款金额
		map.put("total_num", 1);//红包发送总人数
		map.put("wishing", "恭喜您已完成任务！");//红包祝福语
		map.put("client_ip", "114.215.207.119");//ip地址
		map.put("act_name", "微友传单");//活动名称
		map.put("remark", "任务多多，快来领取");//备注
		map.put("sign", MoneyUtils.createSign(map));//签名
		String result = "";
		try {
			result = MoneyUtils.doSendMoney(url, MoneyUtils.createXML(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		System.out.println("result:"+result);
		//result_code SUCCESS 代表成功
		return result;
	}
	
	/**
	 * 公众号支付方法
	 * @param price
	 * @param openid
	 * @return
	 */
	public static String sendPay(int price,String openid){
		
		String mch_billno = MoneyUtils.getMch_billno();
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("appid", "wxca78deeb014de180"); //公众账号ID
		map.put("mch_id", 1419995602);    //商户号
		map.put("nonce_str", MoneyUtils.buildRandom()); //随机字符串
		map.put("body", "微友传单");   //商品描述
		map.put("out_trade_no", mch_billno);  //商户订单号
		map.put("total_fee", price);    //金额   单位分
		map.put("spbill_create_ip", Configure.getIp());  //终端IP
		map.put("notify_url", Configure.getNotifyCallbackUrl());
		map.put("trade_type", "JSAPI");
		map.put("openid", openid);
		map.put("sign", MoneyUtils.createSign(map));//签名
		
		String result = "";
		try {
			result = MoneyUtils.doSendMoney(Configure.PAY_API, MoneyUtils.createXML(map));
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("result:"+result);
		//result_code SUCCESS 代表成功
		return result;
	}
	

	/**
	 * 获取模板消息
	 * @return
	 */
	public static String getMessageModel(WxMessage wm){
		//判断状态；
		String status = wm.getStatus();
		String resultColor=WX_FONT_COLOR_WARN;
		if("1".equals(status)){
			resultColor=WX_FONT_COLOR_NORMAL;
		}
		//templeteId是微信后端模板id
		 String model="{\"touser\":\""+wm.getOpenId()+"\","+
	          "\"template_id\":\""+ "1111"+"\","+
	           "\"url\":\"\","+        
	          " \"data\":{"+
	                 "\"first\": {"+
	                     " \"value\":\""+wm.getFirst()+"\","+
	                      "\"color\":\"\""+
	                  "},"+
	                  "\"keyword1\":{"+
	                      "\"value\":\""+wm.getName()+"\","+
	                       "\"color\":\""+WX_FONT_COLOR_NORMAL+"\""+
	                   "},"+
	                  " \"keyword2\": {"+
	                     "  \"value\":\""+wm.getResult()+"\","+
	                      " \"color\":\""+resultColor+"\""+
	                  " },"+
	                 "  \"keyword3\": {"+
	                      " \"value\":\""+getNowDate("yyyy-MM-dd HH:mm:ss")+"\","+
	                      " \"color\":\""+WX_FONT_COLOR_NORMAL+"\""+
	                   "},"+
	                 "  \"remark\":{"+
	                      " \"value\":\""+wm.getRemark()+"\","+
	                      " \"color\":\""+WX_FONT_COLOR_NORMAL+"\""+
	                 "  }}}";
		
		
		return model;
	}
	
	
	
	public static boolean sendMessage(String message){
		JSONObject response=CommonUtil.httpsRequest("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+CommonUtil.getSingToken(CommonUtil.appId, CommonUtil.appSecret), "post", null);
		System.out.println("消息推送返回结果："+response);
		if(response !=null ){
			return true;
		}
		
		return false;
		
	}
	
	public static String getNowDate(String format){
	SimpleDateFormat df = new SimpleDateFormat(format);//设置日期格式
	return df.format(new Date());
	}
	
	public static SNSUserInfo getUserInfoByCode(String code){
		WeixinOauth2Token oauth2AccessToken = AdvancedUtil.getOauth2AccessToken(CommonUtil.appId, CommonUtil.appSecret, code);
		String accessToken = oauth2AccessToken.getAccessToken();
		String openId = oauth2AccessToken.getOpenId();
		SNSUserInfo snsUserInfo = AdvancedUtil.getSNSUserInfo(accessToken, openId);
		return snsUserInfo;
	}

	public static TreeMap<String, String> Dom2Map(String xml) throws DocumentException {
        Document doc = DocumentHelper.parseText(xml);
        TreeMap<String, String> map = new TreeMap<String, String>();
        if (doc == null)
            return map;
        Element root = doc.getRootElement();
        for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
            Element e = (Element) iterator.next();
            List list = e.elements();
            map.put(e.getName(), e.getText());
        }
        return map;
    }
}
